import {Dom} from "../annotation/Dom.annotation";
import OptionParamsModel from "../model/OptionParams.model";
import { ClassName } from "../config/ClassName.config";
import {Inject} from "../annotation/Ioc.annotation";
import { Utils } from "../utils/index.utils";

/**
 * 视频播放的各种事件监听和处理
 */
export class EventListenersUi {

    @Dom()
    private readonly Play!: HTMLElement;

    @Dom()
    private readonly Video!: HTMLMediaElement;

    @Dom()
    private readonly VideoProgress!: HTMLInputElement;

    @Dom()
    private readonly VideoTime!: HTMLElement;

    @Inject()
    private readonly Utils: Utils;

    // 播放按钮被点击，播放视频
    public BindEventEnded(): void {
        this.Video.addEventListener('ended', () => {
            // 视频播放完成后，将暂停按钮样式改为播放状态
            this.Play.classList.toggle(ClassName.Stop)
            // 回调用户的事件
            OptionParamsModel.OptionParams.finish(this.Video)
        })
    }

    /**
     * 视频播放过程中时间发生改变设置进度条进度
     * @constructor
     */
    public BindEventVideoTimeUpdate() {
        this.Video.ontimeupdate = () => {
            // 进度条前进值 = 当前时间 / 总视频时间 * 100
            let w = this.Video.currentTime / this.Video.duration * 100;

            // 设置进度条已播放过的颜色
            this.VideoProgress.style.backgroundSize = `${w}% 100%`;

            // 设置进度条方块前进值
            this.VideoProgress.value = String(w)
            // 进度条步进值
            this.VideoProgress.step = '0.000000000000000001'
            this.setVideoTime()
        }
    }

    /**
     * 进度条被拖动的时候
     * @constructor
     */
    public BindEventVideoOnProgress(): void {
        this.VideoProgress.oninput = () => {
            // 拿到被拖动滑块的滑动距离
            let offsetX = <any>this.VideoProgress.value;
            // 滑动后对应的视频播放时间  = 滑动距离 / 总距离 * 时间总时间
            this.Video.currentTime = offsetX / 100 * this.Video.duration;
            // 设置进度条已播放过的颜色
            this.VideoProgress.style.backgroundSize = `${offsetX}% 100%`;
            // 拖动的时候自动播放了，所以把播放按钮改成暂停按钮
            this.Play.classList.add(ClassName.Stop)
            this.setVideoTime()

        }
    }

    /**
     * 设置视频的 当前播放时间 / 视频总时间
     */
    public setVideoTime(): void {
        this.VideoTime.innerText = `${this.Utils.formatTime(this.Video.currentTime)}/${this.Utils.formatTime(this.Video.duration)}`;
    }
}
